package com.cloudlead.dictionaryAction.service.impl;
import com.cloudlead.common.lang.persistence.*;
import com.cloudlead.common.worker.security.PasswordHelper;
import com.cloudlead.commonData.service.*;
import com.cloudlead.commonData.vo.*;
import com.cloudlead.dictionaryAction.service.ManagementSer;
import com.cloudlead.dictionaryService.vo.*;
import com.cloudlead.plugin.security.service.ScPrivilegeService;
import com.cloudlead.plugin.security.service.ScUserHasPrivilegeService;
import com.cloudlead.plugin.security.service.ScUserService;
import com.cloudlead.plugin.security.vo.ScPrivilege;
import com.cloudlead.plugin.security.vo.ScUser;
import com.cloudlead.plugin.security.vo.ScUserHasPrivilege;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * Created by Administrator on 2015/10/28.
 */
@Service
public class ManagementSerImpl implements ManagementSer {
    @Autowired
    BaseCompanyUserService baseCompanyUserService;
    @Autowired
    ScUserService scUserService;
    @Autowired
    ScPrivilegeService scPrivilegeService;
    @Autowired
    ScUserHasPrivilegeService scUserHasPrivilegeService;
    @Autowired
    BaseVoyageService baseVoyageService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    TbLogService tbLogService;
    @Autowired
    TbImportLogService tbImportLogService;
    @Autowired
    TbMailLogService tbMailLogService;
    @Autowired
    BaseDockService baseDockService;
    @Autowired
    BaseDoorService baseDoorService;
    @Autowired
    BaseShipRouteService baseShipRouteService;
    @Autowired
    BasePortService basePortService;
    @Autowired
    RegionService regionService;

    @Override
    public Page<BaseCompanyUser> companyList(RegCompanyVo regCompanyVo, int rows, int page) {
        RegCompanyVo vo=regCompanyVo==null?new RegCompanyVo():regCompanyVo;
        PageRequest pr = new PageRequest();
        List<Term> tr = new ArrayList<Term>();
        tr.add(new Term("baseCompany.flag","0"));//未删除
        tr.add(new Term("isAdmin",1));//超级用户
        if(vo.getIdentity()!=null&&!vo.getIdentity().equals("")) {
            tr.add(new Term("baseCompany.identity", vo.getIdentity()));
        }
        if (vo.getStatus()!=null&&!vo.getStatus().equals(""))
            tr.add(new Term("baseCompany.status",vo.getStatus()));//状态
        if (vo.getCompanyName()!=null&&!vo.getCompanyName().equals(""))
            tr.add(new Term("baseCompany.companyName",Operator.LK, "%"+vo.getCompanyName()+"%"));//公司名
        List<Criteria> cts = new ArrayList<Criteria>();
        cts.add(new Criteria(tr));
        Filter filter = new Filter(cts);
        pr.setPage(page);
        pr.setSize(rows);
        pr.setFilter(filter);
        return baseCompanyUserService.findAll(pr);
    }

    @Override
    @Transactional
    public Object audit(String companyId) {
        if (companyId.equals("init sc_user")) return autoCreateScUser();
        try {
            BaseCompany baseCompany = baseCompanyService.view(companyId);
            baseCompany.setStatus("1");
            baseCompanyService.update(baseCompany);
            //管理员
            BaseCompanyUser qryCompanyUser = new BaseCompanyUser();
            qryCompanyUser.setBaseCompany(baseCompany);
            qryCompanyUser.setIsAdmin(1);
            BaseCompanyUser baseCompanyUser = baseCompanyUserService.findOne(qryCompanyUser);
            baseCompanyUser.setStatus("1");
            baseCompanyUserService.update(baseCompanyUser);
            ScUser scUser = new ScUser();
            scUser.setUsername(baseCompanyUser.getUserName());
            scUser.setPassword(PasswordHelper.encryption(baseCompanyUser.getPassword(), null));
            scUser.setMobile(baseCompanyUser.getPhone());
            scUser.setLocked(false);
            scUserService.create(scUser);
            //分配管理员默认权限
            ScPrivilege scPrivilege = new ScPrivilege();
            scPrivilege.setCategorys(Integer.parseInt(baseCompany.getIdentity()));
            List<ScPrivilege> list = scPrivilegeService.list(scPrivilege, null);
            for (int i = 0; i < list.size(); i++) {
                ScUserHasPrivilege scUserHasPrivilege = new ScUserHasPrivilege();
                scUserHasPrivilege.setScUser(scUser);
                scUserHasPrivilege.setScPrivilege(list.get(i));
                scUserHasPrivilege.setIsPermission(true);
                scUserHasPrivilegeService.create(scUserHasPrivilege);
            }
        }catch (Exception e){
            e.printStackTrace();
            e.getMessage();
            return e;
        }
        return "OK";
    }

    @Override
    public Object companyInfo(String id) {
        BaseCompany baseCompany = new BaseCompany();
        baseCompany.setId(id);
        BaseCompanyUser baseCompanyUser = new BaseCompanyUser();
        baseCompanyUser.setFlag("0");
        baseCompanyUser.setIsAdmin(1);
        baseCompanyUser.setBaseCompany(baseCompany);
        BaseCompanyUser bc1 = baseCompanyUserService.findOne(baseCompanyUser);//获取数据库的值
        return bc1;
    }

    @Override
    public Page<BaseVoyage> voyageList(BaseVoyageVo baseVoyageVo,int rows,int page) {
        PageRequest pr = new PageRequest();
        List<Term> tr = new ArrayList<Term>();
        tr.add(new Term("flag", "0"));
        if(baseVoyageVo == null){
            if(baseVoyageVo.getStarPort() != null && !baseVoyageVo.getStarPort().equals("")){
                tr.add(new Term("startDock",baseVoyageVo.getStarPort()));
            }
            if(baseVoyageVo.getDestPort() != null && !baseVoyageVo.getDestPort().equals("")){
                tr.add(new Term("destDock",baseVoyageVo.getDestPort()));
            }
        }
        Filter filter=new Filter(new Criteria(tr));
        pr.setPage(page);
        pr.setSize(rows);
        pr.setFilter(filter);
        baseVoyageService.findAll(pr);
        return baseVoyageService.findAll(pr);
    }

    @Override
    public Page<TbLog> tbLogList(TbLogVo tbLogVo,int rows,int page) {
        PageRequest pr = new PageRequest();
        List<Term> tr = new ArrayList<Term>();
        TbLogVo vo=tbLogVo==null?new TbLogVo():tbLogVo;
        tr.add(new Term("flag","0"));
        if(vo.getId() != null && !vo.getId().equals("")){
            tr.add(new Term("id",vo.getId()));
        }
        if(vo.getOperator() != null && !vo.getOperator().equals("")){
            tr.add(new Term("operator",vo.getOperator()));
        }
        if(vo.getOperationTime() != null && !vo.getOperationTime().equals("")){
            tr.add(new Term("operationTime", vo.getOperationTime()));
        }
        Filter filter=new Filter(new Criteria(tr));
        pr.setPage(page);
        pr.setSize(rows);
        pr.setFilter(filter);
        Page<TbLog> pa = tbLogService.findAll(pr);
        return tbLogService.findAll(pr);
    }

    @Override
    public Page<TbImportLog> importLog(TbImportLogVo tbImportLogVo, int rows, int page) {
        PageRequest pr = new PageRequest();
        List<Term> tr = new ArrayList<Term>();
        TbImportLogVo vo=tbImportLogVo==null?new TbImportLogVo():tbImportLogVo;
        if(vo.getImportResult()!=null&&!vo.getImportResult().equals("")){
            tr.add(new Term("importResult",vo.getImportResult()));
        }
        if(vo.getBussinessCode() != null && !vo.getBussinessCode().equals("")){
            tr.add(new Term("bussinessCode",Operator.LK,"%"+vo.getBussinessCode()+"%"));
        }
        if(vo.getFileName() != null && !vo.getFileName().equals("")){
            tr.add(new Term("fileName",Operator.LK,"%"+vo.getFileName()+"%"));
        }
        Sort sort = new Sort();//创建按导入时间倒序排列
        if(vo!=null) {
            if (!"".equals(vo.getSort()) && vo.getSort() != null && !"".equals(vo.getOrder()) && vo.getOrder() != null) {
                sort.add(new Sort.Order(vo.getOrder().equals("desc") ? Sort.Direction.DESC : Sort.Direction.ASC, vo.getSort()));
            }
        }
        if(tr.size()>0){
        Filter filter=new Filter(new Criteria(tr));
        pr.setFilter(filter);
        }
        pr.setPage(page);
        pr.setSize(rows);
        pr.setSort(sort);
        return tbImportLogService.findAll(pr);
    }

    @Override
    public Page<BaseDock> baseDock(BaseDockVo baseDockVo, int rows, int page) {
        PageRequest pr = new PageRequest();
        List<Term> tr = new ArrayList<Term>();
        BaseDockVo vo=baseDockVo==null?new BaseDockVo():baseDockVo;
        if(vo.getId()!=null&&!vo.getId().equals("")){
            tr.add(new Term("id",vo.getId()));
        }
        if(vo.getName() != null && !vo.getName().equals("")){
            tr.add(new Term("name",Operator.EQ,vo.getName()));
        }
        if(vo.getCode()!=null&&!vo.getCode().equals("")){
            tr.add(new Term("code",Operator.EQ,vo.getCode()));
        }
        if(vo.getPortName()!=null&&!vo.getPortName().equals("")){
            tr.add(new Term("portName",Operator.EQ,vo.getPortName()));
        }
        if(tr.size()>0){
            Filter filter=new Filter(new Criteria(tr));
            pr.setFilter(filter);
        }
        pr.setPage(page);
        pr.setSize(rows);
        return baseDockService.findAll(pr);
    }
    @Override
    public Page<BaseDoor> baseDoor(BaseDoorVo baseDoorVo, int rows, int page) {
        PageRequest pr = new PageRequest();
        List<Term> tr = new ArrayList<Term>();
        BaseDoorVo vo=baseDoorVo==null?new BaseDoorVo():baseDoorVo;
        if(vo.getId()!=null&&!vo.getId().equals("")){
            tr.add(new Term("id",vo.getId()));
        }
        if(vo.getName() != null && !vo.getName().equals("")){
            tr.add(new Term("name", Operator.EQ,vo.getName()));
        }
        if(vo.getFlag()!=null&&!vo.getFlag().equals("")){
            tr.add(new Term("flag",Operator.EQ,vo.getFlag()));
        }
        if(vo.getBasePlaceId()!=null&&!vo.getBasePlaceId().equals("")){
            tr.add(new Term("basePlace.id",Operator.EQ,vo.getBasePlaceId()));
        }
        if(vo.getBaseProvinceId()!=null&&!vo.getBaseProvinceId().equals("")){
            if(vo.getBasePlaceId()==null||vo.getBasePlaceId().equals("")){
                tr.add(new Term("basePlace.id",Operator.EQ,vo.getBaseProvinceId()));
            }
        }
        if(tr.size()>0){
            Filter filter=new Filter(new Criteria(tr));
            pr.setFilter(filter);
        }
        pr.setPage(page);
        pr.setSize(rows);
        return baseDoorService.findAll(pr);
    }

    @Override
    public Page<TbMailLog> mailLog(TbMailLogVo tbMailLogVo, int rows, int page) {
        PageRequest pr = new PageRequest();
        List<Term> tr = new ArrayList<Term>();
        TbMailLogVo vo=tbMailLogVo==null?new TbMailLogVo():tbMailLogVo;
        if(vo.getFileName()!=null&&!vo.getFileName().equals("")){
            tr.add(new Term("fileName",vo.getFileName()));
        }
        if(vo.getMailTo() != null && !vo.getMailTo().equals("")){
            tr.add(new Term("mailTo", Operator.LK, "%" + vo.getMailTo() + "%"));
        }

        Sort sort = new Sort();//创建按发送时间倒序排列
        if(vo!=null) {
            if (!"".equals(vo.getSort()) && vo.getSort() != null && !"".equals(vo.getOrder()) && vo.getOrder() != null) {
                sort.add(new Sort.Order(vo.getOrder().equals("desc") ? Sort.Direction.DESC : Sort.Direction.ASC, vo.getSort()));
            }
        }
        if(tr.size()>0){
            Filter filter=new Filter(new Criteria(tr));
            pr.setFilter(filter);
        }
        pr.setSort(sort);
        pr.setPage(page);
        pr.setSize(rows);

        return tbMailLogService.findAll(pr);
    }

    @Override
    public void delCompany(String companyId) {
        BaseCompany baseCompany = baseCompanyService.view(companyId);
        if(baseCompany.getStatus().equals("1")) {
            BaseCompanyUser baseCompanyUser = new BaseCompanyUser();
            baseCompanyUser.setBaseCompany(baseCompany);
            List<BaseCompanyUser> list = baseCompanyUserService.list(baseCompanyUser, null);
            for (BaseCompanyUser userName : list) {
                userName.setFlag("1");
                baseCompanyUserService.update(userName);
                ScUser scUser = new ScUser();
                scUser.setUsername(userName.getUserName());
                scUser = scUserService.findOne(scUser);
                scUser.setLocked(true);
                scUserService.update(scUser);
            }
            baseCompany.setFlag("1");
            baseCompanyService.update(baseCompany);
        }else{
            BaseCompanyUser baseCompanyUser = new BaseCompanyUser();
            baseCompanyUser.setBaseCompany(baseCompany);
            List<BaseCompanyUser> list = baseCompanyUserService.list(baseCompanyUser, null);
            for (BaseCompanyUser userName : list) {
                baseCompanyUserService.delete(userName.getId());
            }
            baseCompanyService.delete(companyId);
        }
    }

    @Override
    public void delDock(String id){
        /*BaseDock baseDock=baseDockService.view(id);*/
        baseDockService.delete(id);
    }


    //根据base_company_user创建sc_user，并自动分配权限
    @Transactional
    private String autoCreateScUser(){
        BaseCompanyUser qryCompanyUser = new BaseCompanyUser();
        qryCompanyUser.setId("shjinnoo");
    //    qryCompanyUser.setIsAdmin(1);
        List<BaseCompanyUser> userList = baseCompanyUserService.list(qryCompanyUser,null);
        for (BaseCompanyUser baseCompanyUser:userList){
            ScUser scUser = new ScUser();
            scUser.setUsername(baseCompanyUser.getUserName());
            scUser.setPassword(PasswordHelper.encryption("123456", null));
            scUser.setMobile(baseCompanyUser.getPhone());
            scUser.setLocked(false);
            scUserService.create(scUser);
            //分配管理员默认权限
            ScPrivilege scPrivilege = new ScPrivilege();
            scPrivilege.setCategorys(Integer.parseInt(baseCompanyUser.getBaseCompany().getIdentity()));
            List<ScPrivilege> list = scPrivilegeService.list(scPrivilege, null);
            for (int i = 0; i < list.size(); i++) {
                ScUserHasPrivilege scUserHasPrivilege = new ScUserHasPrivilege();
                scUserHasPrivilege.setScUser(scUser);
                scUserHasPrivilege.setScPrivilege(list.get(i));
                scUserHasPrivilege.setIsPermission(true);
                scUserHasPrivilegeService.create(scUserHasPrivilege);
            }
        }
        return "ok";
    }
    //航线
    public Page<BaseShipRoute> baseShipRoute(BaseShipRouteVo baseShipRouteVo,int rows,int page){
        PageRequest pr = new PageRequest();
        List<Term> tr = new ArrayList<Term>();
        BaseShipRouteVo vo=baseShipRouteVo==null?new BaseShipRouteVo():baseShipRouteVo;
        if(vo.getId()!=null&&!vo.getId().equals("")){
            tr.add(new Term("id",vo.getId()));
        }
        if(vo.getStartCity() != null && !vo.getStartCity().equals("")){
            tr.add(new Term("startCity",Operator.EQ,vo.getStartCity()));
        }
        if(vo.getEndCity()!=null&&!vo.getEndCity().equals("")){
            tr.add(new Term("endCity",Operator.EQ,vo.getEndCity()));
        }
        if(vo.getStartPort()!=null&&!vo.getStartPort().equals("")){
            tr.add(new Term("startPort",Operator.EQ,vo.getStartPort()));
        }
        if(vo.getDestPort()!=null&&!vo.getDestPort().equals("")){
            tr.add(new Term("destPort",Operator.EQ,vo.getDestPort()));
        }
        if(vo.getComments()!=null&&!vo.getComments().equals("")){
            tr.add(new Term("comments",Operator.EQ,vo.getComments()));
        }
        if(vo.getFlag()!=null&&!vo.getFlag().equals("")){
            tr.add(new Term("flag",Operator.EQ,vo.getFlag()));
        }
        if(tr.size()>0){
            Filter filter=new Filter(new Criteria(tr));
            pr.setFilter(filter);
        }
        pr.setPage(page);
        pr.setSize(rows);
        return baseShipRouteService.findAll(pr);
    }
    @Override
    public void delShipRoute(String id){
        BaseShipRoute bs=baseShipRouteService.view(id);
        bs.setFlag("1");
        baseShipRouteService.update(bs);
    }
    public String createShipRoute(BaseShipRouteVo vo){
        BaseShipRoute br=new BaseShipRoute();
        BeanUtils.copyProperties(vo, br);
        if(vo.getStartCity()==null||vo.getStartCity().equals("")&&vo.getStartProvince()!=null&&!vo.getStartProvince().equals("")){
            br.setStartCity(vo.getStartProvince());
        }
        if(vo.getEndCity()==null||vo.getEndCity().equals("")&&vo.getEndProvince()!=null&&!vo.getEndProvince().equals("")){
            br.setEndCity(vo.getEndProvince());
        }
        br.setFlag("0");
        baseShipRouteService.create(br);
        return "success";
    }
    public String editShipRoute(BaseShipRouteVo vo){
        BaseShipRoute br=new BaseShipRoute();
        BeanUtils.copyProperties(vo, br);
        if(vo.getStartCity()==null||vo.getStartCity().equals("")&&vo.getStartProvince()!=null&&!vo.getStartProvince().equals("")){
            br.setStartCity(vo.getStartProvince());
        }
        if(vo.getEndCity()==null||vo.getEndCity().equals("")&&vo.getEndProvince()!=null&&!vo.getEndProvince().equals("")){
            br.setEndCity(vo.getEndProvince());
        }
        baseShipRouteService.update(br);
        return "success";
    }
    public List<BasePortVo> findAllPort(BasePortVo vo){
        BasePort bp = new BasePort();
        BeanUtils.copyProperties(vo, bp);//对象类型转换vo-re
        List<BasePort> lr=basePortService.list(bp, null);//列表查询
        List<BasePortVo> lvo = new ArrayList<BasePortVo>();
        for(Iterator<BasePort> it = lr.iterator();it.hasNext();) {//遍历
            BasePortVo rv=new BasePortVo();
            BeanUtils.copyProperties(it.next(), rv);//类型转换
            lvo.add(rv);
        }
        return lvo;
    }
    @Override
    //港口单值查询
    public List findOnePort(BasePortVo vo){
        /*Region region=regionService.view(vo.getCityId());
        BasePort re = new BasePort();
        re.setCity(region);//对象类型转换vo-re
        re=basePortService.findOne(re);//实例查询
        BasePortVo rv = new BasePortVo();
        rv.setId(re.getId());
        rv.setPortCode(re.getPortCode());
        rv.setPortName(re.getPortName());
        rv.setCityId(re.getCity().getId());
        return rv;*/
        Region region=regionService.view(vo.getCityId());
        BasePort bp = new BasePort();
        bp.setCity(region);
        List<BasePort> lr=basePortService.list(bp, null);//列表查询
        List<BasePortVo> lvo = new ArrayList<BasePortVo>();
        for(Iterator<BasePort> it = lr.iterator();it.hasNext();) {//遍历
            BasePortVo rv=new BasePortVo();
            BeanUtils.copyProperties(it.next(), rv);//类型转换
            rv.setCityId(vo.getCityId());
            lvo.add(rv);
        }
        return lvo;
    }
    public Page<BasePort> basePort(BasePortVo vo,int rows,int page){
        PageRequest pr = new PageRequest();
        List<Term> tr = new ArrayList<Term>();
        BasePortVo basePortVo=vo==null?new BasePortVo():vo;
        if(vo.getId()!=null&&!vo.getId().equals("")){
            tr.add(new Term("id",vo.getId()));
        }
        if(vo.getPortName()!=null&&!vo.getPortName().equals("")){
            tr.add(new Term("portName",Operator.EQ,vo.getPortName()));
        }
        if(vo.getPortCode()!=null&&!vo.getPortCode().equals("")){
            tr.add(new Term("portCode",Operator.EQ,vo.getPortCode()));
        }
        if(vo.getCityId()!=null&&!vo.getCityId().equals("")){
            tr.add(new Term("cityId",Operator.EQ,vo.getCityId()));
        }
        if(vo.getCityId()==null||vo.getCityId().equals("")&&vo.getProvinceId()!=null&&!vo.getProvinceId().equals("")){
            tr.add(new Term("cityId",Operator.EQ,vo.getProvinceId()));
        }

        if(tr.size()>0){
            Filter filter=new Filter(new Criteria(tr));
            pr.setFilter(filter);
        }
        pr.setPage(page);
        pr.setSize(rows);
        return basePortService.findAll(pr);
    }
    public void delBasePort(String id){
        basePortService.delete(id);
    }
    public String createPort(BasePortVo vo){
        BasePort bp=new BasePort();
        BeanUtils.copyProperties(vo, bp);
        if(vo.getCityId()!=null&&!vo.getCityId().equals("")){
            Region region=regionService.view(vo.getCityId());
            bp.setCity(region);
        }
        /*if(vo.getCityId()==null||vo.getCityId().equals("")&&vo.getProvinceId()!=null&&!vo.getProvinceId().equals("")){
            Region region=regionService.view(vo.getProvinceId());
            bp.setCity(region);
        }*/
        basePortService.create(bp);
        return "success";
    }
    public String editPort(BasePortVo vo){
        BasePort bp=new BasePort();
        BeanUtils.copyProperties(vo, bp);
        if(vo.getCityId()!=null&&!vo.getCityId().equals("")){
            Region region=regionService.view(vo.getCityId());
            bp.setCity(region);
        }
        /*if(vo.getCityId()==null||vo.getCityId().equals("")&&vo.getProvinceId()!=null&&!vo.getProvinceId().equals("")){
            Region region=regionService.view(vo.getProvinceId());
            bp.setCity(region);
        }*/
        basePortService.update(bp);
       return "success";
    }
}
